<template>
	<el-dialog v-model="visible" width="1000px" :z-index="9" top="3vh" @close="cancel">
		<template #header>
			<div v-if="update" class="custom-header">宣贯培训 新增</div>
			<div v-else class="custom-header">{{ queryParams.trainingName }}{{ isView ? '' : '编辑' }}</div>
		</template>

		<div class="boardBox">
			<el-form ref="queryFormRef" label-width="120px" :model="queryParams" :rules="rules" style="width: 100%">
				<el-form-item label="宣贯培训名称" prop="trainingName">
					<el-input v-model="queryParams.trainingName" placeholder="请输入宣贯培训名称" clearable :disabled="isView" />
				</el-form-item>
				<el-form-item label="标准编号" prop="standardNumber">
					<el-select v-model="queryParams.standardNumber" filterable clearable :disabled="isView">
						<el-option v-for="(item, index) in bzList" :key="index" :label="item" :value="item"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item v-if="!update" label="标准发布日期">
					<el-input v-model="queryParams.publishTime" clearable disabled />
				</el-form-item>
				<el-form-item label="宣贯附件(pdf)">
					<el-upload
						ref="uploadPdfRef"
						drag
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData"
						accept=".pdf"
						:limit="1"
						:file-list="uploadShowPdfList"
						:on-exceed="handleExceed"
						:on-preview="handleUploadPdfPreview"
						:on-success="handleUploadPdfSuccess"
						:on-error="handleUploadPdfError"
						:on-remove="handleUploadPdfRemove"
						:disabled="isView"
					>
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-form-item label="培训视频">
					<el-upload
						ref="uploadPdfRef"
						drag
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData2"
						accept=".mp4, .avi, .mov, wmv, .flv"
						:limit="1"
						:file-list="uploadShowVideoList"
						:on-exceed="handleExceed"
						:on-preview="handleUploadVideoPreview"
						:on-success="handleUploadVideoSuccess"
						:on-error="handleUploadVideoError"
						:on-remove="handleUploadVideoRemove"
						:before-upload="beforeUploadVideo"
						:disabled="isView"
					>
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>

				<el-form-item label="宣贯内容" style="width: 100%">
					<el-input v-if="isView" v-model="queryParams.trainingContent" type="textarea" :rows="10" disabled style="width: 100%"></el-input>
					<ma-editor v-else v-model="queryParams.trainingContent"></ma-editor>
				</el-form-item>
			</el-form>
		</div>
		<div class="dialog-footer">
			<el-button v-if="Number(queryParams.applyStatus) == 1 && userStore.user.roleCode.includes('SHZZ')" type="primary" @click="handleApprove"
				>确认</el-button
			>
			<el-button
				v-if="Number(queryParams.applyStatus) == 0 || Number(queryParams.applyStatus) == 5 || queryParams.applyStatus == ''"
				@click="handleAddFormSubmit(queryFormRef, false)"
				>暂存</el-button
			>
			<el-button
				v-if="Number(queryParams.applyStatus) == 0 || Number(queryParams.applyStatus) == 5"
				type="primary"
				@click="handleAddFormSubmit(queryFormRef, true)"
				>提交</el-button
			>
			<el-button @click="cancel">关闭</el-button>
		</div>
	</el-dialog>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { htmlToText } from 'html-to-text'
import moment from 'moment'
import { reactive, ref } from 'vue'

import { approvalApi, GetBzListApi, saveOrSubmitApi } from '@/api/standardapplication/index'

import { filePreviewByName } from '@/api/sys/upload'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

const props = defineProps({
	isView: {
		type: Boolean,
		default: false
	}
})
const visible = ref(false)
const update = ref(false)
// 获取表单引用
const queryFormRef = ref<FormInstance>()
const uploadRef = ref(null)
// 新增字段
const queryParams = ref({
	trainingName: '',
	standardNumber: '',
	trainingFileId: '',
	trainingVideoFileId: '',
	trainingContent: '',
	hasSubmit: true,
	applyStatusValue: '',
	applyStatus: 0
})
const showPublishTime = ref(moment().format('YYYY-MM-DD'))
// 子父交互
// const emit = defineEmits<{(event: 'update:visible', value: boolean): void; (event: 'chananniu', value: ''): void }>()
const emit = defineEmits(['refreshDataList'])
// 监听 localValue 的变化，通知父组件更新值
// watch(
// 	() => props.visible,
// 	newValue => {
// 		if (newValue) {
// 			const data = {
//         trainingName: '',
//         standardNumber: '',
//         trainingFileId: '',
//         trainingVideoFileId: '',
//         trainingContent: '',
//         hasSubmit: true
//       }
//       showPublishTime.value = moment().format('YYYY-MM-DD')
// 			queryParams.value = data
// 		}
// 	}
// )
// 校验
const rules = reactive<FormRules>({
	trainingName: [{ required: true, message: '请输入宣贯培训名称', trigger: 'blur' }],
	standardNumber: [{ required: true, message: '请输入标准编号', trigger: 'blur' }]
})
// 上传操作
const filelist = reactive([])
const uploadPdfRef = ref<UploadInstance>()
const uploadShowPdfList = ref<UploadRawFile[]>([])
const uploadShowVideoList = ref<UploadRawFile[]>([])
interface UploadFile {
	id: String
	extCode: String
	fileExtName: String
	filePath: String
	fileRealName: String
	fileSize: number
	remark: String
	systemFileName: String
}
const uploadPdfList = ref<UploadFile[]>([])
const uploadVideoList = ref<UploadFile[]>([])

const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'PromotionTrainiing',
	remark: '宣贯附件'
}

const uploadData2 = {
	extCode: 'TrainiingVideo',
	remark: '培训视频'
}

const bzList = ref([])

const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}
// 预览文件
const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}
const handleUploadPdfSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadPdfList.value = []
		uploadPdfList.value.push(res.data)
		console.log(uploadPdfList.value)
	} else {
		handleUploadPdfError(res, uploadFile)
	}
}
const handleUploadPdfError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowPdfList.value = uploadShowPdfList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}
const handleUploadPdfRemove = (file: UploadRawFile) => {
	uploadPdfList.value = []
}
// 视频
const handleUploadVideoPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}
const handleUploadVideoSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadVideoList.value = []
		uploadVideoList.value.push(res.data)
		console.log('视频成功：', uploadVideoList.value)
	} else {
		handleUploadVideoError(res, uploadFile)
	}
}
const handleUploadVideoError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowVideoList.value = uploadShowVideoList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}
const handleUploadVideoRemove = (file: UploadRawFile) => {
	uploadVideoList.value = []
}
const beforeUploadVideo = (file: UploadRawFile) => {
	const fileSize = file.size / 1024 / 1024
	if (fileSize > 200) {
		ElMessage.error('文件大小不能超过200M!')
		return false
	}
	// const fileReg = /.mp4|.avi|.mov/;
	// if (!fileReg.test(file.name)) {
	//   ElMessage.error('请选择.mp4, .avi, .mov格式文件');
	//   return false;
	// }
	return true
}

// ==============文件上传结束==================

interface saveObject {
	trainingName?: string
	standardNumber?: string
	trainingFileId?: string
	trainingVideoFileId?: string
	trainingContent?: string
	hasSubmit?: Boolean
	// publishStatus?: Number | String,
	// publishTime?:  string
}
const handleAddFormSubmit = async (formEl: FormInstance | undefined, flag: boolean) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			submitData(flag)
			formEl?.resetFields()
		} else {
			console.log('提交错误', fields)
		}
	})
}
const submitData = async (flag: Boolean) => {
	var obj: saveObject = Object.create(null)
	// delete queryParams.value["traingContent"]
	// delete queryParams.value["applyStatus"]
	// delete queryParams.value["applyStatusValue"]
	// delete queryParams.value["trainingFile"]
	// delete queryParams.value["trainingVideoFile"]
	// 文件列表
	// if (!Array.isArray(uploadPdfList.value)) return [];
	// if(uploadPdfList.value.length > 0) {
	//   // queryParams.value["trainingFileId"] = uploadPdfList.value[0]["id"]
	//   queryParams.value["trainingFileId"] = uploadPdfList.value[0]["systemFileName"]
	// }
	// if(uploadVideoList.value.length > 0) {
	//   queryParams.value["trainingVideoFileId"] = uploadVideoList.value[0]["systemFileName"]
	// }
	let text = htmlToText(queryParams.value['trainingContent'])
	obj = {
		trainingName: queryParams.value['trainingName'],
		standardNumber: queryParams.value['standardNumber'],
		trainingContent: text,
		trainingFileId: uploadPdfList.value.length > 0 ? uploadPdfList.value[0]['id'] : '',
		trainingVideoFileId: uploadVideoList.value.length > 0 ? uploadVideoList.value[0]['id'] : '',
		hasSubmit: flag,
		id: queryParams.value['id'] ? queryParams.value['id'] : ''
	}
	await saveOrSubmitApi(obj).then(res => {
		cancel()
	})
}

// 审批
const handleApprove = async () => {
	var obj = {
		applyStatus: '2',
		id: queryParams.value['id']
	}
	await approvalApi(obj).then(res => {
		ElMessage({
			type: 'success',
			message: '审批成功'
		})
		cancel()
	})
}
const cancel = () => {
	visible.value = false
	uploadShowPdfList.value = []
	uploadShowVideoList.value = []
	uploadPdfList.value = []
	uploadVideoList.value = []
	// emit('update:visible', false)
	emit('refreshDataList')
}
// true新增  、false编辑
// 0：未提交  编辑
// 1：已提交未处理  审核
// 2：通过   发布
// 3：通过并发布
// 4：不通过
// 5: 退回修改   编辑
const init = (isUpdate: boolean, row: any) => {
	getBz()
	update.value = isUpdate
	if (isUpdate) {
		// 重置画面数据
		const czobj = {
			trainingName: '',
			standardNumber: '',
			trainingFileId: '',
			trainingVideoFileId: '',
			trainingContent: '',
			hasSubmit: false,
			applyStatusValue: '',
			applyStatus: 0,
			id: ''
		}
		uploadShowPdfList.value = []
		uploadShowVideoList.value = []
		showPublishTime.value = moment().format('YYYY-MM-DD')
		queryParams.value = czobj
	} else {
		row['trainingContent'] = row.traingContent
		// 文件处理
		if (row.trainingFile) {
			uploadShowPdfList.value = [
				{
					name: row.trainingFile['fileName'],
					url: row.trainingFile['systemFileName'],
					systemFileName: row.trainingFile['systemFileName'],
					id: row.trainingFile['id']
				}
			]
			uploadPdfList.value = uploadShowPdfList.value
		}

		if (row.trainingVideoFile) {
			uploadShowVideoList.value = [
				{
					name: row.trainingVideoFile['fileName'],
					url: row.trainingFile['systemFileName'],
					systemFileName: row.trainingFile['systemFileName'],
					id: row.trainingFile['id']
				}
			]
			uploadVideoList.value = uploadShowVideoList.value
		}
		Object.assign(queryParams.value, row)
	}
	visible.value = true
	console.log(queryParams.value)
}

const getBz = () => {
	GetBzListApi({
		pageIndex: 1,
		pageSize: 1000
	}).then(res => {
		bzList.value = res.data
	})
}

defineExpose({
	init
})
</script>

<style lang="scss" scoped>
.boardBox {
	display: flex;
	align-items: center;
	flex-direction: column;

	overflow-y: scroll;
	height: calc(100vh - 210px);

	&::-webkit-scrollbar {
		display: none;
	}

	-ms-overflow-style: none;
	scrollbar-width: none;

	.tishi {
		font-size: 14px;
		color: #999;
		background-color: #f3f8fb;
		padding: 5px 10px;
		border-radius: 6px;
	}
}
</style>
